package order.application.service;

import order.domain.model.Order;
import order.domain.model.OrderItem;
import order.domain.repository.OrderRepository;
import order.domain.repository.OrderItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private OrderItemRepository orderItemRepository;

    public void createOrder(Order order) {
        order.setCreateAt(LocalDateTime.now());
        // 1. 先保存订单，orderId 会自动生成
        orderRepository.save(order);
        // 2. 获取订单项列表
        List<OrderItem> items = order.getItems();
        if (items != null && !items.isEmpty()) {
            for (OrderItem item : items) {
                item.setOrder(order); // 建立OrderItem和Order的关联
            }
            // 3. 批量保存订单项
            orderItemRepository.saveAll(items);
        }
    }

    public List<Order> getAllOrders() {
        return orderRepository.findAll();
    }

    public Order getOrderById(Long id) {
        return orderRepository.findById(id);
    }

    public List<Order> getOrdersByCustomer(Long customerId) {
        return orderRepository.findByCustomerId(customerId);
    }

    public void deleteOrder(Long id) {
        orderRepository.delete(id);
    }
}